<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
namespace App\Http;
use Session;
function httpRequest($url,$data=null)
{   
    $curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,false);  //1：回复内容 0：输出内容
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,false); 
	if (!empty($data)) {
		curl_setopt($curl, CURLOPT_POST, 1); //模拟post方式
		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	}
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	//执行事务
	$output = curl_exec($curl);
	//关闭
	curl_close($curl);
	//输出内容
	return $output;	
}

$app->get('/', function(){
	if(isset($_GET['code'])){
		$data   = [
	            "client_id"     => env("TABLE_CLIENT_ID"),
	            "client_secret" => env("TABLE_CLIENT_SECRET"),
	            "grant_type"    => "authorization_code",
	            "code"          => $_GET["code"]
	    ];
	    $tokenResponse = httpRequest(env("OAUTH_URL")."/oauth2/token",$data);
	    $tokenResponse = json_decode($tokenResponse,true);
	    if($tokenResponse['error'] == true)
	        return "auth error";

	    $result = $tokenResponse['result'];
	    Session::put('user_id',$result['user_id']);
	    Session::put('authorization',$result['token_type']." ".$result['access_token']);
	    Session::save();
	    if(!empty($_GET["state"]))
	        return redirect($_GET["state"]);
	}
});

$app->get ('/table',									     	'App\Http\Controllers\TableController@index');
$app->configure('ptime');
$api = app('Dingo\Api\Routing\Router');

$api->version('v1', function ($api) {
	//教务
	$api->get('/week',											 'App\Http\Controllers\DataController@getWeek');
	$api->post ('/table',									     'App\Http\Controllers\TableController@store');

	//通用
	$api->get 	('/{table:[A-Z_a-z]+}/config', 					 'App\Http\Controllers\ApiController@config');
	$api->post 	('/file', 					                	 'App\Http\Controllers\ApiController@upload');
	$api->get 	('/{table:[A-Z_a-z]+}', 						 'App\Http\Controllers\ApiController@index');
	$api->get 	('/{table:[A-Z_a-z]+}/{id:[0-9]+}', 			 'App\Http\Controllers\ApiController@show');
	$api->post 	('/{table:[A-Z_a-z]+}', 						 'App\Http\Controllers\ApiController@store');
	$api->put 	('/{table:[A-Z_a-z]+}/{id:[0-9]+}', 			 'App\Http\Controllers\ApiController@update');
	$api->delete('/{table:[A-Z_a-z]+}/{id:[0-9]+}', 			 'App\Http\Controllers\ApiController@destroy');
	$api->get 	('/config/init', 								 'App\Http\Controllers\ConfigController@init');

	//数据流
	$api->get('/data/table',									 'App\Http\Controllers\DataController@table');
});

